package com.zsh.rabbitmq.one;

import com.rabbitmq.client.*;


import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zsh
 * @Description 消费者，接收消息
 * @create 2022-04-26 12:42
 */
public class Consumer {
    //队列名称
    public static final String QUEUE_NAME = "hello";

    //接收消息
    public static void main(String[] args) throws Exception {
        //创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("192.168.200.128");
        factory.setUsername("admin");
        factory.setPassword("123456");

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //声明 接收消息 lambda 表达式
        DeliverCallback deliverCallback = (consumerTag, msg) -> {
            String msgString = new String(msg.getBody());
            System.out.println(msgString);
        };

        //声明 取消消息 lambda 表达式
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消息被中断");
        };

        //消费者接收消息
        /*
        1. 消费哪个队列
        2. 消费成功之后是否要自动应答 true 自动 false 手动
        3. 消费者未成功消费的回调
        4. 消费者取消消费的回调
         */
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }
}
